<template>
  <div class="collect-container">
    <div class="header">
      <h2>我的收藏</h2>
      <div class="actions">
        <button 
          v-if="selectedItems.length > 0" 
          @click="handleBatchDelete" 
          class="batch-delete-btn"
        >
          删除选中 ({{ selectedItems.length }})
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <p>加载中...</p>
    </div>

    <!-- 空状态 -->
    <div v-else-if="favorites.length === 0" class="empty-state">
      <p>暂无收藏的帖子</p>
    </div>

    <!-- 收藏列表 -->
    <div v-else class="favorites-list">
      <div class="list-header">
        <label class="checkbox-container">
          <input 
            type="checkbox" 
            v-model="selectAll"
            @change="handleSelectAll"
          >
          <span class="checkmark"></span>
          全选
        </label>
        <span class="total-count">共 {{ pageInfo.total || 0 }} 条收藏</span>
      </div>

      <div class="favorite-item" v-for="item in favorites" :key="item.favoriteId">
        <label class="checkbox-container">
          <input 
            type="checkbox" 
            :value="item.favoriteId"
            v-model="selectedItems"
          >
          <span class="checkmark"></span>
        </label>
        
        <div class="item-content" @click="goToDetail(item.favoriteId)">
          <h3 class="post-title">{{ item.title }}</h3>
          <div class="post-info">
            <span class="tag" v-if="item.tag">{{ item.tag }}</span>
            <span class="collect-time">收藏时间：{{ formatDate(item.favoriteCreatedAt) }}</span>
          </div>
        </div>
        
        <div class="item-actions">
          <button @click="goToDetail(item.favoriteId)" class="detail-btn">查看详情</button>
          <button @click="handleSingleDelete(item.favoriteId)" class="delete-btn">取消收藏</button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="favorites.length > 0" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total || 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import axios from 'axios';
import { useUserStore } from '@/store/user';
import { useRouter } from 'vue-router';
import { ElPagination, ElMessage, ElMessageBox } from 'element-plus';

const userStore = useUserStore();
const router = useRouter();

// 响应式数据
const favorites = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(5);
const pageInfo = ref({}); // 存储完整的分页信息
const selectedItems = ref([]);
const selectAll = ref(false);

// 监听选中项变化
watch(selectedItems, (newVal) => {
  selectAll.value = newVal.length === favorites.value.length && favorites.value.length > 0;
});

// 监听全选状态
watch(selectAll, (newVal) => {
  if (newVal) {
    selectedItems.value = favorites.value.map(item => item.favoriteId);
  } else {
    selectedItems.value = [];
  }
});

// 获取分页数据（参考 studentList 的 getPageData 方法）
const getPageData = async (pageNum, pageSizeVal) => {
  loading.value = true;
  try {
    const userId = userStore.userId;
    if (!userId) {
      console.error('用户未登录');
      ElMessage.warning('请先登录');
      return;
    }
    
    console.log('请求参数:', { pageNum, pageSize: pageSizeVal, userId });
    
    const response = await axios.get(`/user/post/favorites/${userId}`, {
      params: {
        current: pageNum,  // 后端期望的参数名
        size: pageSizeVal  // 后端期望的参数名
      }
    });
    
    console.log('后端返回数据:', response.data);
    
    if (response && response.data) {
      // 完全参照 studentList 的数据处理方式
      pageInfo.value = response.data;
      favorites.value = Array.isArray(response.data.list) ? response.data.list : [];
      
      console.log('处理后的数据:', {
        pageInfo: pageInfo.value,
        favorites: favorites.value,
        total: pageInfo.value.total
      });
      
    } else {
      favorites.value = [];
      pageInfo.value = {};
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error);
    ElMessage.error('获取收藏列表失败，请稍后重试');
    favorites.value = [];
    pageInfo.value = {};
  } finally {
    loading.value = false;
  }
};

// 每页大小变化（完全参照 studentList 的实现）
const handleSizeChange = (pageSizeVal) => {
  pageSize.value = pageSizeVal;
  getPageData(currentPage.value, pageSize.value);
  console.log("size", pageSizeVal);
};

// 当前页变化（完全参照 studentList 的实现）
const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getPageData(currentPage.value, pageSize.value);
  console.log("num", pageNum);
};

// 全选/取消全选
const handleSelectAll = () => {
  if (selectAll.value) {
    selectedItems.value = favorites.value.map(item => item.favoriteId);
  } else {
    selectedItems.value = [];
  }
};

// 跳转到详情页
const goToDetail = (favoriteId) => {
  router.push({ name: 'CollectionDetail', params: { id: favoriteId } });
};

// 单个删除（参考 studentList 的 singleDelete 方法）
const handleSingleDelete = async (favoriteId) => {
  try {
    await ElMessageBox.confirm(
      '您确定要取消收藏这个帖子吗?',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
    );

    const response = await axios.delete(`/user/post/favorites/${favoriteId}`);
    
    console.log('删除响应:', response.data);
    
    if (response.data === true) {
      ElMessage({
        type: 'success',
        message: '取消收藏成功',
      });
      
      // 重新加载当前页数据
      getPageData(currentPage.value, pageSize.value);
    } else {
      ElMessage({
        type: 'warning',
        message: '取消收藏失败',
      });
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除收藏失败:', error);
      ElMessage({
        type: 'error',
        message: '取消收藏失败，请重试',
      });
    } else {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      });
    }
  } finally {
    // 清除选中状态
    selectedItems.value = selectedItems.value.filter(id => id !== favoriteId);
  }
};

// 批量删除（参考 studentList 的 multiDelete 方法）
const handleBatchDelete = async () => {
  if (selectedItems.value.length === 0) {
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `您确定要取消收藏选中的 ${selectedItems.value.length} 个帖子吗?`,
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
    );

    let successCount = 0;
    
    // 逐个删除（参考 studentList 的实现）
    for (const favoriteId of selectedItems.value) {
      try {
        const response = await axios.delete(`/user/post/favorites/${favoriteId}`);
        if (response.data === true) {
          successCount++;
        }
      } catch (error) {
        console.error(`删除收藏 ${favoriteId} 失败:`, error);
      }
    }
    
    ElMessage({
      type: 'success',
      message: `成功取消收藏 ${successCount} 条记录`,
    });
    
    // 重新加载当前页数据
    getPageData(currentPage.value, pageSize.value);
    
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('批量删除收藏失败:', error);
      ElMessage({
        type: 'error',
        message: '批量取消收藏失败，请重试',
      });
    } else {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      });
    }
  } finally {
    selectedItems.value = [];
    selectAll.value = false;
  }
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  try {
    const d = new Date(date);
    if (isNaN(d.getTime())) {
      return date;
    }
    return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
  } catch (error) {
    return date;
  }
};

// 组件挂载时获取数据（参考 studentList 的 mounted）
onMounted(async () => {
  await userStore.initialize();
  getPageData(1, 5); // 初始加载第一页，每页5条
});
</script>

<style scoped>
.collect-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.header h2 {
  color: #333;
  margin: 0;
}

.batch-delete-btn {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.batch-delete-btn:hover {
  background-color: #ff7875;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 60px;
  color: #999;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 15px;
}

.total-count {
  color: #666;
  font-size: 14px;
}

.favorite-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  margin-bottom: 10px;
  transition: all 0.3s;
}

.favorite-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-color: #d9d9d9;
}

.checkbox-container {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-right: 15px;
  font-size: 14px;
}

.checkbox-container input[type="checkbox"] {
  margin-right: 8px;
  transform: scale(1.2);
}

.item-content {
  flex: 1;
  cursor: pointer;
  min-width: 0;
}

.post-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.post-info {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 12px;
  color: #666;
}

.tag {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.collect-time {
  color: #999;
}

.item-actions {
  display: flex;
  gap: 10px;
  margin-left: 15px;
}

.detail-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s;
}

.detail-btn {
  background-color: #1890ff;
  color: white;
}

.detail-btn:hover {
  background-color: #40a9ff;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
}

.delete-btn:hover {
  background-color: #ff7875;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  padding: 20px;
}

@media (max-width: 768px) {
  .collect-container {
    padding: 15px;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .favorite-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .item-content {
    width: 100%;
  }
  
  .item-actions {
    margin-left: 0;
    width: 100%;
    justify-content: flex-end;
  }
  
  .list-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .pagination {
    flex-direction: column;
    gap: 10px;
  }
}
</style>